﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 单线程使用的随机数(为了和C#在随机因子相同时产生相同随机数)
/// 
/// @author heyang
/// 
/// </summary>
public class RandomFactory
{

    private static readonly long mask = (1L << 48) - 1;
    private const long multiplier = 0x5DEECE66DL;
    private const long addend = 11L;

    public long seed;

    private static long InitialScramble(long seed)
    {
        return (seed ^ multiplier) & mask;
    }

    public RandomFactory(long seed)
    {
        this.seed = InitialScramble(seed);
    }

    private int Next(int bits)
    {
        long oldseed, nextseed;
        long seed = this.seed;
        oldseed = seed;
        nextseed = (oldseed * multiplier + addend) & mask;
        this.seed = nextseed;
        return (int)((long)((ulong)nextseed >> (48 - bits)));
    }

    public virtual int NextInt(int bound)
    {
        if (bound <= 0)
        {
            return 0;
        }

        int r = Next(31);
        int m = bound - 1;
        if ((bound & m) == 0) // i.e., bound is a power of 2
        {
            r = (int)((bound * (long)r) >> 31);
        }
        else
        {
            for (int u = r; u - (r = u % bound) + m < 0; u = Next(31))
            {
                ;
            }
        }
        return r;
    }
}